package com.jdjr.drools.core.util;

import cn.hutool.core.util.StrUtil;
import com.jdjr.drools.entity.Rules;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import java.util.List;

@Log4j
public class DroolsUtils {

    public static void reload(String rules, List<?> facts) {
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kfs = kieServices.newKieFileSystem();
        kfs.write("src/main/resources/rules/rule.drl", rules);

        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
        Results results = kieBuilder.getResults();
        if (results.hasMessages(Message.Level.ERROR)) {
            throw new RuntimeException("获取规则出现异常");
        }
        KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());

        KieSession kieSession = kieContainer.newKieSession();
        for (Object fact : facts) {
            kieSession.insert(fact);
            log.info("Inserting fact:" + fact);
        }
        kieSession.fireAllRules();

        log.info("规则处理完成");
    }

    /**
     * 组装规则
     *
     * @param rules
     * @return
     */
    public static String installRule(Rules rules) {
        return StrUtil.format("package {} {} rule {} {} when {} then {} end", rules.getPackageName(), StringUtils.isBlank(rules.getImports()) ? "" : "import " + rules.getImports(), rules.getRuleName(), StringUtils.isBlank(rules.getAttributes()) ? "" : rules.getAttributes(), StringUtils.isBlank(rules.getLhs()) ? "" : rules.getLhs(), StringUtils.isBlank(rules.getRhs()) ? "" : rules.getRhs());
    }

}
